/*
 * Created on Thu Oct 30 10:29:26 GMT+01:00 2008
 */
package org.germinus.cardea.MuleServiceBundle.impl;


import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;
import org.osgi.framework.Constants;
import org.osgi.framework.ServiceEvent;
import org.osgi.framework.ServiceListener;
import org.osgi.util.tracker.ServiceTracker;
import org.knopflerfish.service.log.LogService;


public class Activator implements BundleActivator, ServiceListener{
  
  /* (non-Javadoc)
   * @see org.osgi.framework.BundleActivator#start(org.osgi.framework.BundleContext)
   */
	
	public static BundleContext bc=null;
	//private MuleContext mulecontext=null;
	private StockConsumer stock=null;
	protected ServiceTracker tracker;
	protected static LogService log;
	private ContextBean cbean;
	private static DateFormat df = new SimpleDateFormat("yyyy-MM-dd'/'HH:mm");
	
  public void start(BundleContext context) throws Exception {
	  
	  System.out.println(context.getBundle().getHeaders().get(Constants.BUNDLE_NAME)+ " starting...");
	  Activator.bc = context;
	  
	  tracker=new ServiceTracker(context, LogService.class.getName(), null);
	  tracker.open();
	  log=(LogService)tracker.getService();
	  bc.addServiceListener(this, "(objectclass=" + LogService.class.getName()+")" );
	 
	  System.out.println("Crea el bean desde Activator");
	  cbean = ContextBean.getContextBean();
	  cbean.setContext(context);
		
		//Creamos los consumidores del stock
		//Arrancamos los threads y los guardamos en Context bean
		stock=new StockConsumer("ESB", context);
		stock.start();
		cbean.setConsumer(stock);
		
  }

  /* (non-Javadoc)
   * @see org.osgi.framework.BundleActivator#stop(org.osgi.framework.BundleContext)
   */
  public void stop(BundleContext context) throws Exception {
	  
	  System.out.println(context.getBundle().getHeaders().get(Constants.BUNDLE_NAME)+ " stopping..."); 

	  stock.stop();
	  stock=null;
	  log=null;

	  Activator.bc = null;
	  cbean.stopContext();
  }
  
  public static void log(String message){
		if (log == null){
			System.out.println(df.format(new Date())+" [ESB bundle] Log is NULL");
			return;
			
		}
		message = df.format(new Date())+" [ESB_BUNDLE]:"+message;
		log.log(LogService.LOG_INFO, message);
	}


  public void serviceChanged(ServiceEvent event) {
	// TODO Auto-generated method stub
	if (event.getType()==ServiceEvent.REGISTERED)
		log = (LogService) bc.getService(event.getServiceReference());
	else if(event.getType()==ServiceEvent.UNREGISTERING)
		log=null;
	
}
 
}